<?php

namespace App\Service\users;

use App\Events\UsersAmountEvent;
use App\Models\users\UsersAlipayModel;
use App\Models\users\UsersBankModel;
use App\Models\users\UsersWithdrawOrderInfoModel;
use App\Models\users\UsersWithdrawOrderModel;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use lxs\config\BaseStatic;
use lxs\tools\Tools;

class WithdrawService extends BaseStatic
{

    /**
     * 获取提现数据（web）
     */
    public function getWithdrawData(int $uid, int $page, int $pageSize, $searchData=[]): LengthAwarePaginator
    {
        $query = UsersWithdrawOrderModel::with(['orderInfo'])
            ->where('uid', $uid)
            ->where('deleted_at', 0);

        if (isset($searchData['data_time']) && $searchData['data_time'] != '') {
            $query->where(function ($query) use ($searchData) {
                $query->where('create_time', '>=', strtotime($searchData['data_time'][0]))
                    ->where('create_time', '<=', strtotime($searchData['data_time'][1]));
            });
        }

        $lists = $query->orderBy('create_time', 'desc')
            ->paginate($pageSize, ['*'], 'page', $page);
        foreach ($lists as $key => $val) {
            $lists[$key]['type_value'] = UsersWithdrawOrderModel::getwithdrawType($val['type']);
        }
        return $lists;
    }


    /**
     * 用户提现表单提交(小程序)
     */
    public function userWithdrawSubmit($uid, $formData): array
    {
        try {
            DB::beginTransaction();

            $userInfo = UsersService::instance()->getUserInfo($uid);
            if ($formData['withdraw_money'] > $userInfo->amount) {
                return self::serviceReturn(400, '提现金额不能大于账户余额');
            }

            $withDraw = new UsersWithdrawOrderModel();
            $withDraw->order_sn = Tools::uniqidDate('TX_');
            $withDraw->uid = $userInfo->id;
            $withDraw->type = UsersWithdrawOrderModel::WITHDRAW_TYPE[$formData['change_type']];
            $withDraw->amount = $formData['amount'];
            $withDraw->commission = $formData['commission'];
            $withDraw->real_amount = $formData['withdraw_money'];
            $withDraw->remark = $formData['remark'] ?? '';
            $withDraw->status = UsersWithdrawOrderModel::WITHDRAW_APPLYING;
            $withDraw->create_time = time();
            $withDraw->save();

            $payee = $payee_account = $remark = '';
            if ($withDraw->type == 1) {
                $payee = $userInfo->nickname;
                $payee_account = $userInfo->mobile;
                $remark = '微信提现';
            } else if ($withDraw->type == 2) {
                $bankInfo = UsersBankModel::where('uid', $userInfo->id)->first();
                $payee = $bankInfo->payee;
                $payee_account = $bankInfo->bank_number;
                $remark = $bankInfo->bank_name . $bankInfo->bank_info;
            } else if ($withDraw->type == 3) {
                $alipayInfo = UsersAlipayModel::where('uid', $userInfo->id)->first();
                $payee = $alipayInfo->payee_name;
                $payee_account = $alipayInfo->payee_account;
                $remark = '支付宝提现';
            }

            if ( isset($withDraw->id) ) {
                // 添加提现订单其他信息
                $info = new UsersWithdrawOrderInfoModel();
                $info->order_id = $withDraw->id;
                $info->payee = $payee;
                $info->account = $payee_account;
                $info->remark = $remark;
                $info->save();
                // 账户变动
                $data = [
                    'uid' => $userInfo->id,
                    'num' => $formData['amount'] == 0 ? 0 : 0 - $formData['amount'],
                    'credit_type' => AccountRecordService::USER_AMOUNT,
                    'type' => AccountRecordService::TYPE_WITHDRAW,
                    'table_id' => $withDraw->id,
                    'remark' => '申请提现：' . $formData['amount'] . '元',
                    'operator' => 'user',
                ];
                event(new UsersAmountEvent($data));
            }

            DB::commit();
            return self::serviceReturn(200, '提交成功', ['withdraw_id' => $withDraw->id]);
        } catch (\Throwable $e) {
            DB::rollBack();
            Log::error('用户提现表单提交异常：' . $e->getMessage() . $e->getLine());
            return self::serviceReturn(400, '用户提现表单提交执行失败');
        }
    }


    /**
     * 用户提现驳回处理
     * @param int $withdraw_id 提现记录ID
     * @param string $examineReason 驳回原因
     * @param string $operator 操作人
     * @return array
     */
    public function withdrawRejectHandle(int $withdraw_id, string $examineReason, string $operator): array
    {
        try {
            DB::beginTransaction();

            $withdraw = UsersWithdrawOrderModel::where('id', $withdraw_id)->first();

            $withdraw->status = 2;
            $withdraw->examine_reason = $examineReason;
            $withdraw->examine_time = time();
            $withdraw->examine_operator = $operator;
            $withdraw->save();

            if ( isset($withdraw->id) ) {
                // 账户变动
                $data2 = [
                    'uid' => $withdraw->uid,
                    'num' => 0 + $withdraw['amount'],
                    'credit_type' => AccountRecordService::USER_AMOUNT,
                    'type' => AccountRecordService::TYPE_WITHDRAW,
                    'table_id' => $withdraw->id,
                    'remark' => '提现驳回，退还余额：' . $withdraw['amount'] . '元',
                    'operator' => 'user',
                ];
                event(new UsersAmountEvent($data2));
            }

            DB::commit();
            return self::serviceReturn(200, '用户提现记录驳回提交成功');

        } catch (\Exception $e) {
            DB::rollBack();
            Log::error('用户提现驳回处理: ' . $e->getMessage() . $e->getLine());
            return self::serviceReturn(304, '用户提现记录驳回提交失败');
        }
    }


}
